<% title t("views.subforems.edit.meta.title", subforem: @subforem.domain) %>

<main id="main-content" class="manage-page-with-sidebar">
  <!-- Sidebar Navigation -->
  <aside class="manage-sidebar crayons-card" id="manage-sidebar">
    <nav class="manage-sidebar-nav">
      <h3 class="manage-sidebar-title">Sections</h3>
      <ul class="manage-sidebar-list">
        <% if current_user.any_admin? %>
          <li><a href="#section-basic" class="manage-sidebar-link" data-section="section-basic">Basic Info</a></li>
          <li><a href="#section-discoverability" class="manage-sidebar-link" data-section="section-discoverability">Discoverability</a></li>
        <% end %>
        <li><a href="#section-community" class="manage-sidebar-link" data-section="section-community">Community Settings</a></li>
        <li><a href="#section-feed" class="manage-sidebar-link" data-section="section-feed">Feed & Content</a></li>
        <li><a href="#section-branding" class="manage-sidebar-link" data-section="section-branding">Branding</a></li>
        <li><a href="#section-tags" class="manage-sidebar-link" data-section="section-tags">Supported Tags</a></li>
        <li><a href="#section-pages" class="manage-sidebar-link" data-section="section-pages">Pages</a></li>
        <li><a href="#section-nav-links" class="manage-sidebar-link" data-section="section-nav-links">Navigation Links</a></li>
        <li><a href="#section-bots" class="manage-sidebar-link" data-section="section-bots">Community Bots</a></li>
      </ul>
    </nav>
  </aside>

  <!-- Main Content -->
  <div class="manage-main-content">
    <nav class="mb-4">
      <h1 class="crayons-title mb-2">
        <%= t("views.subforems.edit.heading", subforem: @subforem.domain) %>
        <span class="crayons-tag crayons-tag--s crayons-tag--monochrome ml-2 fs-s"><%= t("views.subforems.edit.beta_badge") %></span>
      </h1>
    </nav>

    <%= form_for @subforem, html: { multipart: true } do |form| %>
      
      <!-- SECTION 1: Basic Information (Admin only) -->
      <% if current_user.any_admin? %>
        <div class="crayons-card p-6 mb-4" id="section-basic">
          <h2 class="crayons-title mb-4"><%= t("views.subforems.edit.sections.basic_information") %></h2>
          <div class="flex flex-col gap-4">
            <div class="crayons-field">
              <%= form.label :domain, class: "crayons-field__label" %>
              <%= form.text_field :domain, class: "crayons-textfield" %>
            </div>

            <div class="crayons-field">
              <%= label_tag :community_name, t("views.subforems.edit.form.community_name.label"), class: "crayons-field__label" %>
              <%= text_field_tag :community_name,
                Settings::Community.community_name(subforem_id: @subforem.id),
                class: "crayons-textfield",
                placeholder: t("views.subforems.edit.form.community_name.placeholder") %>
              <p class="crayons-field__description"><%= t("views.subforems.edit.form.community_name.description") %></p>
            </div>
          </div>
        </div>
      <% end %>

      <!-- SECTION 1.5: Discoverability (Admin only) -->
      <% if current_user.any_admin? %>
        <div class="crayons-card p-6 mb-4" id="section-discoverability">
          <h2 class="crayons-title mb-4"><%= t("views.subforems.edit.sections.discoverability") %></h2>
          <div class="flex flex-col gap-4">
            <div class="crayons-field">
              <%= form.label :discoverable, t("views.subforems.edit.form.discoverable.label"), class: "crayons-field__label" %>
              <%= form.check_box :discoverable, class: "crayons-checkbox" %>
              <p class="crayons-field__description"><%= t("views.subforems.edit.form.discoverable.description") %></p>
            </div>
          </div>
        </div>
      <% end %>

      <!-- SECTION 2: Community Settings -->
      <div class="crayons-card p-6 mb-4" id="section-community">
        <h2 class="crayons-title mb-4"><%= t("views.subforems.edit.sections.community_settings") %></h2>
        <div class="flex flex-col gap-4">
            <div class="crayons-field">
              <%= label_tag :community_description, t("views.subforems.edit.form.community_description.label"), class: "crayons-field__label" %>
              <%= text_area_tag :community_description,
                Settings::Community.community_description(subforem_id: @subforem.id),
                class: "crayons-textfield", rows: 4,
                placeholder: t("views.subforems.edit.form.community_description.placeholder") %>
              <p class="crayons-field__description"><%= t("views.subforems.edit.form.community_description.description") %></p>
            </div>

            <div class="crayons-field">
              <%= label_tag :tagline, t("views.subforems.edit.form.tagline.label"), class: "crayons-field__label" %>
              <%= text_field_tag :tagline,
                Settings::Community.tagline(subforem_id: @subforem.id),
                class: "crayons-textfield",
                placeholder: t("views.subforems.edit.form.tagline.placeholder") %>
              <p class="crayons-field__description"><%= t("views.subforems.edit.form.tagline.description") %></p>
            </div>

            <div class="crayons-field">
              <%= label_tag :member_label, t("views.subforems.edit.form.member_label.label"), class: "crayons-field__label" %>
              <%= text_field_tag :member_label,
                Settings::Community.member_label(subforem_id: @subforem.id),
                class: "crayons-textfield",
                placeholder: t("views.subforems.edit.form.member_label.placeholder") %>
              <p class="crayons-field__description"><%= t("views.subforems.edit.form.member_label.description") %></p>
          </div>
        </div>
      </div>

      <!-- SECTION 3: Feed & Content Settings -->
      <div class="crayons-card p-6 mb-4" id="section-feed">
        <h2 class="crayons-title mb-4"><%= t("views.subforems.edit.sections.feed_settings") %></h2>
        <div class="flex flex-col gap-4">
            <div class="crayons-field">
              <%= label_tag :feed_style, t("views.subforems.edit.form.feed_style.label"), class: "crayons-field__label" %>
              <%= select_tag :feed_style,
                options_for_select(
                  [[t("views.subforems.edit.form.feed_style.options.basic"), "basic"], 
                   [t("views.subforems.edit.form.feed_style.options.rich"), "rich"], 
                   [t("views.subforems.edit.form.feed_style.options.compact"), "compact"]],
                  Settings::UserExperience.feed_style(subforem_id: @subforem.id)
                ),
                class: "crayons-select" %>
              <p class="crayons-field__description"><%= t("views.subforems.edit.form.feed_style.description") %></p>
            </div>

            <div class="crayons-field">
              <%= label_tag :feed_lookback_days, t("views.subforems.edit.form.feed_lookback_days.label"), class: "crayons-field__label" %>
              <%= number_field_tag :feed_lookback_days,
                Settings::UserExperience.feed_lookback_days(subforem_id: @subforem.id),
                class: "crayons-textfield",
                min: 1,
                max: 365,
                placeholder: t("views.subforems.edit.form.feed_lookback_days.placeholder") %>
              <p class="crayons-field__description"><%= t("views.subforems.edit.form.feed_lookback_days.description") %></p>
            </div>

            <div class="crayons-field">
              <%= label_tag :internal_content_description_spec, t("views.subforems.edit.form.internal_content_spec.label"), class: "crayons-field__label" %>
              <%= text_area_tag :internal_content_description_spec,
                Settings::RateLimit.internal_content_description_spec(subforem_id: @subforem.id),
                class: "crayons-textfield", rows: 4,
                placeholder: t("views.subforems.edit.form.internal_content_spec.placeholder") %>
              <p class="crayons-field__description"><%= t("views.subforems.edit.form.internal_content_spec.description") %></p>
            </div>

            <div class="crayons-field">
              <%= label_tag :sidebar_tags, t("views.subforems.edit.form.sidebar_tags.label"), class: "crayons-field__label" %>
              <%= text_field_tag :sidebar_tags,
                Settings::General.sidebar_tags(subforem_id: @subforem.id).join(","),
                class: "crayons-textfield",
                placeholder: t("views.subforems.edit.form.sidebar_tags.placeholder"),
                pattern: "[a-z0-9,]+" %>
              <p class="crayons-field__description"><%= t("views.subforems.edit.form.sidebar_tags.description") %></p>
          </div>
        </div>
      </div>

      <!-- SECTION 4: Branding -->
      <div class="crayons-card p-6 mb-4" id="section-branding">
        <h2 class="crayons-title mb-4"><%= t("views.subforems.edit.sections.branding") %></h2>
        <div class="flex flex-col gap-4">
            <div class="crayons-field">
              <%= label_tag :primary_brand_color_hex, t("views.subforems.edit.form.primary_color.label"), class: "crayons-field__label" %>
              <div class="flex items-center gap-2">
                <%= text_field_tag :primary_brand_color_hex,
                  Settings::UserExperience.primary_brand_color_hex(subforem_id: @subforem.id),
                  class: "crayons-textfield",
                  placeholder: t("views.subforems.edit.form.primary_color.placeholder"),
                  pattern: "#[a-fA-F0-9]{6}|#[a-fA-F0-9]{3}" %>
                <input type="color" 
                       value="<%= Settings::UserExperience.primary_brand_color_hex(subforem_id: @subforem.id) %>"
                       onchange="document.getElementById('primary_brand_color_hex').value = this.value"
                       class="h-10 w-10 rounded cursor-pointer">
              </div>
              <p class="crayons-field__description"><%= t("views.subforems.edit.form.primary_color.description") %></p>
            </div>

            <div class="crayons-field">
              <%= label_tag :cover_image_aesthetic_instructions, t("views.subforems.edit.form.cover_image_aesthetic.label"), class: "crayons-field__label" %>
              <%= text_area_tag :cover_image_aesthetic_instructions,
                Settings::UserExperience.cover_image_aesthetic_instructions(subforem_id: @subforem.id),
                class: "crayons-textfield", rows: 3,
                placeholder: t("views.subforems.edit.form.cover_image_aesthetic.placeholder") %>
              <p class="crayons-field__description"><%= t("views.subforems.edit.form.cover_image_aesthetic.description") %></p>
            </div>

            <% if current_user.any_admin? || current_user.super_moderator? %>
              <div class="crayons-field" data-controller="subforem-image-upload">
                <%= form.label :main_logo, t("views.subforems.edit.form.main_logo.label"), class: "crayons-field__label" %>
                <p class="crayons-field__description"><%= t("views.subforems.edit.form.main_logo.description") %></p>
                <div class="flex flex-1 gap-4">
                  <%= form.file_field :main_logo, 
                      accept: "image/png,image/jpg,image/jpeg,.png,.jpg,.jpeg", 
                      data: { 
                        "max-file-size-mb": "8",
                        action: "change->subforem-image-upload#previewImage",
                        "image-type": "main_logo"
                      } %>
                  <div data-subforem-image-upload-target="preview" class="w-25 h-25" style="width: 100px">
                    <% if Settings::General.logo_png(subforem_id: @subforem.id).present? %>
                      <img src="<%= Settings::General.logo_png(subforem_id: @subforem.id) %>" 
                           alt="Main logo preview" 
                           style="width: 100px"
                           class="object-cover rounded">
                    <% end %>
                  </div>
                </div>
              </div>
              
              <div class="crayons-field" data-controller="subforem-image-upload">
                <%= form.label :nav_logo, t("views.subforems.edit.form.nav_logo.label"), class: "crayons-field__label" %>
                <p class="crayons-field__description"><%= t("views.subforems.edit.form.nav_logo.description") %></p>
                <div class="flex flex-1 gap-4">
                  <%= form.file_field :nav_logo, 
                      accept: "image/png,image/jpg,image/jpeg,.png,.jpg,.jpeg", 
                      data: { 
                        "max-file-size-mb": "8",
                        action: "change->subforem-image-upload#previewImage",
                        "image-type": "nav_logo"
                      } %>
                  <div data-subforem-image-upload-target="preview" class="w-25 h-25" style="width: 100px">
                    <% if Settings::General.resized_logo(subforem_id: @subforem.id).present? %>
                      <img src="<%= Settings::General.resized_logo(subforem_id: @subforem.id) %>" 
                           alt="Nav logo preview" 
                           style="width: 100px"
                           class="object-cover rounded">
                    <% end %>
                  </div>
                </div>
              </div>
              
              <div class="crayons-field" data-controller="subforem-image-upload">
                <%= form.label :social_card, t("views.subforems.edit.form.social_card.label"), class: "crayons-field__label" %>
                <p class="crayons-field__description"><%= t("views.subforems.edit.form.social_card.description") %></p>
                <div class="flex flex-1 gap-4">
                  <%= form.file_field :social_card, 
                      accept: "image/png,image/jpg,image/jpeg,.png,.jpg,.jpeg", 
                      data: { 
                        "max-file-size-mb": "8",
                        action: "change->subforem-image-upload#previewImage",
                        "image-type": "social_card"
                      } %>
                  <div data-subforem-image-upload-target="preview" class="w-25" style="width: 100px">
                    <% if Settings::General.main_social_image(subforem_id: @subforem.id).present? %>
                      <img src="<%= Settings::General.main_social_image(subforem_id: @subforem.id) %>" 
                           alt="Social card preview" 
                           style="width: 100px"
                           class="object-cover rounded">
                    <% end %>
                  </div>
                </div>
              </div>
          <% end %>
        </div>
      </div>

      <div class="mt-6 mb-4">
        <%= form.submit t("views.subforems.edit.form.submit_button"), class: "crayons-btn crayons-btn--primary" %>
      </div>
    <% end %>

    <!-- SECTION: Supported Tags -->
    <div class="crayons-card p-6 mb-4" id="section-tags">
      <h2 class="crayons-title mb-4"><%= t("views.subforems.edit.tags.supported_heading") %></h2>

      <% if @supported_tags.any? %>
        <div class="space-y-2 mb-6" style="max-height: 550px; overflow-y: auto;">
          <% @supported_tags.each do |tag| %>
            <div class="flex items-center justify-between p-2 bg-base-5 rounded-lg" data-supported-tag-id="<%= tag.id %>">
              <div class="flex items-center gap-2">
                <a href="/t/<%= tag.name %>" class="crayons-tag crayons-tag--monochrome"><%= tag.name %></a>
                <span class="text-xs color-base-60"><%= t("views.subforems.edit.tags.posts_count", count: tag.taggings_count) %></span>
              </div>
              <button class="crayons-btn crayons-btn--s crayons-btn--danger remove-tag-btn" 
                      data-tag-id="<%= tag.id %>" 
                      data-tag-name="<%= tag.name %>">
                <%= t("views.subforems.edit.tags.remove_button") %>
              </button>
            </div>
          <% end %>
        </div>
      <% else %>
        <p class="text-sm color-base-60 mb-6"><%= t("views.subforems.edit.tags.no_tags") %></p>
      <% end %>

      <h2 class="crayons-subtitle-2 mb-4"><%= t("views.subforems.edit.tags.unsupported_heading") %></h2>

      <% if @unsupported_tags.any? %>
        <div class="space-y-2" style="max-height: 550px; overflow-y: auto;">
          <% @unsupported_tags.each do |tag| %>
            <div class="flex items-center justify-between p-2 bg-base-5 rounded-lg" data-tag-id="<%= tag.id %>">
              <a href="/t/<%= tag.name %>" class="crayons-tag crayons-tag--monochrome"><%= tag.name %></a>
              <div class="flex items-center gap-2">
                <span class="text-xs color-base-60"><%= t("views.subforems.edit.tags.posts_count", count: tag.taggings_count) %></span>
                <button class="crayons-btn crayons-btn--s crayons-btn--primary add-tag-btn" 
                        data-tag-id="<%= tag.id %>" 
                        data-tag-name="<%= tag.name %>">
                  <%= t("views.subforems.edit.tags.add_button") %>
                </button>
              </div>
            </div>
          <% end %>
        </div>
      <% else %>
        <p class="text-sm color-base-60"><%= t("views.subforems.edit.tags.no_unsupported_tags") %></p>
      <% end %>
    </div>

    <!-- PAGES SECTION -->
    <div class="crayons-card p-6 mb-4" id="section-pages">
      <div class="flex items-center justify-between mb-4">
        <div>
          <h2 class="crayons-title"><%= t("views.subforems.edit.pages.heading") %></h2>
        </div>
        <%= link_to t("views.subforems.edit.pages.create_button"), new_page_subforem_path(@subforem), class: "crayons-btn crayons-btn--s crayons-btn--primary" %>
      </div>
      <div class="mb-4">
        <p class="text-sm color-base-60 mt-1"><%= t("views.subforems.edit.pages.subheading_html") %></p>
      </div>
      <% if @pages.any? %>
        <div class="space-y-3">
          <% @pages.each do |page| %>
          <div class="flex items-center justify-between p-3 bg-base-5 rounded-lg">
            <div class="flex-1">
              <div class="font-medium">
                <%= page.title %>
                <% if page.is_top_level_path %>
                  <span class="crayons-tag crayons-tag--s crayons-tag--monochrome ml-2"><%= t("views.subforems.edit.pages.top_level_badge") %></span>
                <% end %>
              </div>
              <div class="text-sm color-base-60"><%= page.description %></div>
              <div class="text-xs color-base-50">
                <%= t("views.subforems.edit.pages.slug_label") %>: <%= page.slug %> | 
                <%= t("views.subforems.edit.pages.path_label") %>: <%= page.is_top_level_path ? "/#{page.slug}" : "/page/#{page.slug}" %>
              </div>
            </div>
            <div class="flex items-center gap-2">
              <%= link_to t("views.subforems.edit.pages.view_button"), page.path, class: "crayons-btn crayons-btn--s crayons-btn--outlined", target: "_blank" %>
              <%= link_to t("views.subforems.edit.pages.edit_button"), edit_page_subforem_path(@subforem, page_id: page.id), class: "crayons-btn crayons-btn--s crayons-btn--secondary" %>
              <% unless page.is_top_level_path %>
                <%= button_to t("views.subforems.edit.pages.delete_button"), 
                    destroy_page_subforem_path(@subforem, page_id: page.id), 
                    method: :delete, 
                    data: { confirm: t("views.subforems.edit.pages.delete_confirm") },
                    class: "crayons-btn crayons-btn--s crayons-btn--danger" %>
              <% end %>
            </div>
            </div>
          <% end %>
        </div>
      <% else %>
        <p class="text-sm color-base-60"><%= t("views.subforems.edit.pages.no_pages") %></p>
      <% end %>
    </div>

    <!-- NAVIGATION LINKS SECTION -->
    <div class="crayons-card p-6 mb-4" id="section-nav-links">
      <div class="flex items-center justify-between mb-4">
        <h2 class="crayons-title"><%= t("views.subforems.edit.navigation_links.heading") %></h2>
        <button type="button" class="crayons-btn crayons-btn--s crayons-btn--primary" onclick="toggleNavLinkForm()"><%= t("views.subforems.edit.navigation_links.add_button") %></button>
      </div>
      
      <!-- Add Navigation Link Form -->
    <div id="nav-link-form" class="mb-4 p-4 bg-base-5 rounded-lg" style="display: none;">
      <%= form_tag(create_navigation_link_subforem_path(@subforem), method: :post, multipart: true) do %>
        <div class="grid gap-4">
          <div class="crayons-field">
            <%= label_tag 'navigation_link[name]', t("views.subforems.edit.navigation_links.form.name.label"), class: "crayons-field__label" %>
            <%= text_field_tag 'navigation_link[name]', nil, class: "crayons-textfield", placeholder: t("views.subforems.edit.navigation_links.form.name.placeholder"), required: true %>
          </div>

          <div class="crayons-field">
            <%= label_tag 'navigation_link[url]', t("views.subforems.edit.navigation_links.form.url.label"), class: "crayons-field__label" %>
            <%= text_field_tag 'navigation_link[url]', nil, class: "crayons-textfield", placeholder: t("views.subforems.edit.navigation_links.form.url.placeholder"), required: true %>
          </div>

          <div class="crayons-field">
            <%= label_tag 'navigation_link[image]', t("views.subforems.edit.navigation_links.form.image.label"), class: "crayons-field__label" %>
            <%= file_field_tag 'navigation_link[image]', accept: "image/png,image/jpg,image/jpeg,.png,.jpg,.jpeg", class: "crayons-textfield" %>
            <p class="crayons-field__description"><%= t("views.subforems.edit.navigation_links.form.image.description") %></p>
          </div>

          <div class="crayons-field">
            <button type="button" class="c-link c-link--block mb-2" onclick="toggleSvgIconField('create')">
              <span id="svg-toggle-create">+ <%= t("views.subforems.edit.navigation_links.form.icon.alternative") %></span>
            </button>
            <div id="svg-icon-field-create" style="display: none;">
              <%= label_tag 'navigation_link[icon]', t("views.subforems.edit.navigation_links.form.icon.label"), class: "crayons-field__label" %>
              <%= text_area_tag 'navigation_link[icon]', nil, class: "crayons-textfield", rows: 3, placeholder: t("views.subforems.edit.navigation_links.form.icon.placeholder") %>
              <p class="crayons-field__description"><%= t("views.subforems.edit.navigation_links.form.icon.description") %></p>
            </div>
          </div>

          <div class="grid grid-cols-3 gap-4">
            <div class="crayons-field">
              <%= label_tag 'navigation_link[section]', t("views.subforems.edit.navigation_links.form.section.label"), class: "crayons-field__label" %>
              <%= select_tag 'navigation_link[section]', 
                  options_for_select([[t("views.subforems.edit.navigation_links.form.section.options.default"), "default"], 
                                      [t("views.subforems.edit.navigation_links.form.section.options.other"), "other"]], "default"),
                  class: "crayons-select" %>
            </div>

            <div class="crayons-field">
              <%= label_tag 'navigation_link[display_to]', t("views.subforems.edit.navigation_links.form.display_to.label"), class: "crayons-field__label" %>
              <%= select_tag 'navigation_link[display_to]', 
                  options_for_select([[t("views.subforems.edit.navigation_links.form.display_to.options.all"), "all"], 
                                      [t("views.subforems.edit.navigation_links.form.display_to.options.logged_in"), "logged_in"], 
                                      [t("views.subforems.edit.navigation_links.form.display_to.options.logged_out"), "logged_out"]], "all"),
                  class: "crayons-select" %>
            </div>

            <div class="crayons-field">
              <%= label_tag 'navigation_link[position]', t("views.subforems.edit.navigation_links.form.position.label"), class: "crayons-field__label" %>
              <%= number_field_tag 'navigation_link[position]', 0, class: "crayons-textfield", min: 0 %>
            </div>
          </div>

          <div class="flex gap-2">
            <%= submit_tag t("views.subforems.edit.navigation_links.form.create_button"), class: "crayons-btn crayons-btn--primary" %>
            <button type="button" class="crayons-btn crayons-btn--ghost" onclick="toggleNavLinkForm()"><%= t("views.subforems.edit.navigation_links.form.cancel_button") %></button>
          </div>
        </div>
      <% end %>
    </div>

    <!-- Edit Navigation Link Forms (Hidden by default) -->
    <% @navigation_links.each do |link| %>
      <div id="edit-nav-link-form-<%= link.id %>" class="mb-4 p-4 bg-base-5 rounded-lg" style="display: none;">
        <%= form_tag(update_navigation_link_subforem_path(@subforem, link.id), method: :patch, multipart: true) do %>
          <div class="grid gap-4">
            <div class="crayons-field">
              <%= label_tag 'navigation_link[name]', "Name", class: "crayons-field__label" %>
              <%= text_field_tag 'navigation_link[name]', link.name, class: "crayons-textfield", required: true %>
            </div>

            <div class="crayons-field">
              <%= label_tag 'navigation_link[url]', "URL", class: "crayons-field__label" %>
              <%= text_field_tag 'navigation_link[url]', link.url, class: "crayons-textfield", required: true %>
            </div>

            <div class="crayons-field">
              <%= label_tag 'navigation_link[image]', t("views.subforems.edit.navigation_links.form.image.label"), class: "crayons-field__label" %>
              <% if link.respond_to?(:image) && link.image.present? %>
                <div class="mb-2">
                  <div class="text-sm color-base-60 mb-1"><%= t("views.subforems.edit.navigation_links.form.image.current") %></div>
                  <%= optimized_image_tag(link.image.url, optimizer_options: { width: 48, height: 48, crop: "fill" }, image_options: { alt: "Current icon", style: "width: 48px; height: 48px;" }) %>
                </div>
              <% end %>
              <%= file_field_tag 'navigation_link[image]', accept: "image/png,image/jpg,image/jpeg,.png,.jpg,.jpeg", class: "crayons-textfield" %>
              <p class="crayons-field__description"><%= t("views.subforems.edit.navigation_links.form.image.description_edit") %></p>
            </div>

            <div class="crayons-field">
              <button type="button" class="c-link c-link--block mb-2" onclick="toggleSvgIconField('edit-<%= link.id %>')">
                <span id="svg-toggle-edit-<%= link.id %>">+ <%= t("views.subforems.edit.navigation_links.form.icon.alternative") %></span>
              </button>
              <div id="svg-icon-field-edit-<%= link.id %>" style="display: none;">
                <%= label_tag 'navigation_link[icon]', t("views.subforems.edit.navigation_links.form.icon.label"), class: "crayons-field__label" %>
                <%= text_area_tag 'navigation_link[icon]', link.icon, class: "crayons-textfield", rows: 3 %>
                <p class="crayons-field__description"><%= t("views.subforems.edit.navigation_links.form.icon.description") %></p>
              </div>
            </div>

            <div class="grid grid-cols-3 gap-4">
              <div class="crayons-field">
                <%= label_tag 'navigation_link[section]', "Section", class: "crayons-field__label" %>
                <%= select_tag 'navigation_link[section]', 
                    options_for_select([["Default", "default"], ["Other", "other"]], link.section),
                    class: "crayons-select" %>
              </div>

              <div class="crayons-field">
                <%= label_tag 'navigation_link[display_to]', "Display To", class: "crayons-field__label" %>
                <%= select_tag 'navigation_link[display_to]', 
                    options_for_select([["All", "all"], ["Logged In", "logged_in"], ["Logged Out", "logged_out"]], link.display_to),
                    class: "crayons-select" %>
              </div>

              <div class="crayons-field">
                <%= label_tag 'navigation_link[position]', "Position", class: "crayons-field__label" %>
                <%= number_field_tag 'navigation_link[position]', link.position, class: "crayons-textfield", min: 0 %>
              </div>
            </div>

            <div class="flex gap-2">
              <%= submit_tag "Update Link", class: "crayons-btn crayons-btn--primary" %>
              <button type="button" class="crayons-btn crayons-btn--ghost" onclick="toggleEditNavLinkForm(<%= link.id %>)">Cancel</button>
            </div>
          </div>
        <% end %>
      </div>
    <% end %>
    
    <% if @navigation_links.any? %>
      <div class="space-y-3">
        <% @navigation_links.each do |link| %>
          <div class="flex items-center justify-between p-3 bg-base-5 rounded-lg" id="nav-link-<%= link.id %>">
            <div class="flex-1">
              <div class="font-medium flex items-center gap-2">
                <% if link.respond_to?(:image) && link.image.present? %>
                  <%= optimized_image_tag(link.image.url, optimizer_options: { width: 24, height: 24, crop: "fill" }, image_options: { alt: "#{link.name} icon", style: "width: 16px; height: 16px;" }) %>
                <% else %>
                  <span class="text-sm" style="width: 16px; height: 16px;"><%= link.icon.html_safe %></span>
                <% end %>
                <%= link.name %>
              </div>
              <div class="text-sm color-base-60">
                <a href="<%= link.url %>" target="_blank" class="c-link c-link--branded"><%= link.url %></a>
              </div>
              <div class="text-xs color-base-50">
                <%= t("views.subforems.edit.navigation_links.section_label") %>: <%= link.section %> | 
                <%= t("views.subforems.edit.navigation_links.display_label") %>: <%= link.display_to %> | 
                <%= t("views.subforems.edit.navigation_links.position_label") %>: <%= link.position %>
              </div>
            </div>
            <div class="flex items-center gap-2">
              <button type="button" class="crayons-btn crayons-btn--s crayons-btn--secondary" onclick="toggleEditNavLinkForm(<%= link.id %>)"><%= t("views.subforems.edit.navigation_links.edit_button") %></button>
              <%= button_to t("views.subforems.edit.navigation_links.delete_button"), 
                  destroy_navigation_link_subforem_path(@subforem, navigation_link_id: link.id), 
                  method: :delete, 
                  data: { confirm: t("views.subforems.edit.navigation_links.delete_confirm") },
                  class: "crayons-btn crayons-btn--s crayons-btn--danger" %>
            </div>
          </div>
          <% end %>
        </div>
      <% else %>
        <p class="text-sm color-base-60"><%= t("views.subforems.edit.navigation_links.no_links") %></p>
      <% end %>
    </div>

    <!-- COMMUNITY BOTS SECTION -->
    <div class="crayons-card p-6 mb-4" id="section-bots">
      <div class="flex items-center justify-between mb-4">
        <h2 class="crayons-title"><%= t("views.subforems.edit.community_bots.heading") %></h2>
        <% if current_user.any_admin? %>
          <%= link_to t("views.subforems.edit.community_bots.manage_button"), admin_subforem_community_bots_path(@subforem), class: "crayons-btn crayons-btn--s" %>
        <% end %>
      </div>

      <% unless current_user.any_admin? %>
        <div class="crayons-notice crayons-notice--info mb-4">
          <%= t("views.subforems.edit.community_bots.moderator_notice_html") %>
        </div>
      <% end %>
      
      <% community_bots = User.community_bots_for_subforem(@subforem.id).includes(:api_secrets).order(created_at: :desc) %>
      
      <% if community_bots.any? %>
        <div class="space-y-3">
          <% community_bots.each do |bot| %>
          <div class="flex items-center justify-between p-3 bg-base-5 rounded-lg">
            <div class="flex-1">
              <div class="font-medium flex items-center gap-2">
                <span class="text-lg">🤖</span>
                <%= bot.name %>
                <span class="text-sm color-base-60">@<%= bot.username %></span>
              </div>
              <div class="text-sm color-base-60">
                <%= bot.email %>
              </div>
              <div class="text-xs color-base-50">
                <%= t("views.subforems.edit.community_bots.created_label") %>: <%= bot.created_at.strftime("%b %d, %Y") %> | 
                <%= t("views.subforems.edit.community_bots.api_secrets_label") %>: <%= bot.api_secrets.count %>
              </div>
            </div>
            <div class="flex items-center gap-2">
              <% if current_user.any_admin? %>
                <%= link_to t("views.subforems.edit.community_bots.view_button"), admin_subforem_community_bot_path(@subforem, bot), class: "crayons-btn crayons-btn--s crayons-btn--secondary" %>
              <% end %>
            </div>
            </div>
          <% end %>
        </div>
      <% else %>
        <p class="text-sm color-base-60"><%= t("views.subforems.edit.community_bots.no_bots") %></p>
      <% end %>
    </div>

    <!-- COMING SOON SECTION -->
    <div class="crayons-card p-6 mb-12" id="section-coming-soon" style="margin-bottom: 200px">
      <h2 class="crayons-title mb-4">Coming Soon</h2>
      <div class="crayons-notice crayons-notice--info">
        <p class="mb-2">
          <strong>These features are rapidly evolving!</strong>
        </p>
        <p>
          Visit <a href="https://core.forem.com" target="_blank" rel="noopener noreferrer" class="crayons-link underline">core.forem.com</a> for up-to-date information about what is being shipped and to stay informed about new subforem capabilities.
        </p>
        <p>
          Contact the Forem team for any additional support.
      </div>
    </div>
  </div>
</main>

<script>
// Toggle navigation link form
function toggleNavLinkForm() {
  const form = document.getElementById('nav-link-form');
  form.style.display = form.style.display === 'none' ? 'block' : 'none';
}

// Toggle edit navigation link form
function toggleEditNavLinkForm(linkId) {
  const form = document.getElementById(`edit-nav-link-form-${linkId}`);
  const navLink = document.getElementById(`nav-link-${linkId}`);
  
  if (form.style.display === 'none') {
    form.style.display = 'block';
    navLink.style.display = 'none';
  } else {
    form.style.display = 'none';
    navLink.style.display = 'flex';
  }
}

function initializeSubforemEditPage() {
  const addTagButtons = document.querySelectorAll('.add-tag-btn');
  const removeTagButtons = document.querySelectorAll('.remove-tag-btn');
  
  // Sync color picker with text input
  const colorInput = document.getElementById('primary_brand_color_hex');
  const colorPicker = document.querySelector('input[type="color"]');
  
  if (colorInput && colorPicker) {
    colorInput.addEventListener('input', function() {
      if (this.value.match(/^#[0-9A-Fa-f]{6}$/)) {
        colorPicker.value = this.value;
      }
    });
  }
  
  // Add tag functionality
  addTagButtons.forEach(button => {
    button.addEventListener('click', function(e) {
      e.preventDefault();
      
      const tagId = this.dataset.tagId;
      const tagName = this.dataset.tagName;
      const button = this;
      
      // Disable button and show loading state
      button.disabled = true;
      button.textContent = 'Adding...';
      
      // Make AJAX request
      fetch(`/subforems/<%= @subforem.id %>/add_tag`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        },
        body: JSON.stringify({ tag_id: tagId })
      })
      .then(response => response.json())
      .then(data => {
        if (data.success) {
          // Move the tag from unsupported to supported section
          const tagElement = button.closest('[data-tag-id]');
          const supportedSection = document.querySelector('.space-y-2.mb-6');
          
          if (supportedSection) {
            // Create new supported tag element
            const newSupportedTag = document.createElement('div');
            newSupportedTag.className = 'flex items-center justify-between p-2 bg-base-5 rounded-lg';
            newSupportedTag.setAttribute('data-supported-tag-id', tagId);
            newSupportedTag.innerHTML = `
              <div class="flex items-center gap-2">
                <a href="/t/${tagName}" class="crayons-tag crayons-tag--monochrome">${tagName}</a>
                <span class="text-xs color-base-60">0 posts</span>
              </div>
              <button class="crayons-btn crayons-btn--s crayons-btn--danger remove-tag-btn" 
                      data-tag-id="${tagId}" 
                      data-tag-name="${tagName}">
                Remove
              </button>
            `;
            
            // Add to supported section
            supportedSection.appendChild(newSupportedTag);
            
            // Attach event listener to new remove button
            const newRemoveBtn = newSupportedTag.querySelector('.remove-tag-btn');
            attachRemoveTagListener(newRemoveBtn);
            
            // Remove from unsupported section
            tagElement.remove();
            
            // Show success message
            showNotification('Tag added successfully!', 'success');
          }
        } else {
          showNotification(data.message || 'Failed to add tag', 'error');
        }
      })
      .catch(error => {
        console.error('Error:', error);
        showNotification('An error occurred while adding the tag', 'error');
      })
      .finally(() => {
        // Re-enable button
        button.disabled = false;
        button.textContent = 'Add';
      });
    });
  });
  
  // Remove tag functionality
  function attachRemoveTagListener(button) {
    button.addEventListener('click', function(e) {
      e.preventDefault();
      
      if (!confirm('Are you sure you want to remove this tag from the supported tags?')) {
        return;
      }
      
      const tagId = this.dataset.tagId;
      const tagName = this.dataset.tagName;
      const button = this;
      
      // Disable button and show loading state
      button.disabled = true;
      button.textContent = 'Removing...';
      
      // Make AJAX request
      fetch(`/subforems/<%= @subforem.id %>/remove_tag`, {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json',
          'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        },
        body: JSON.stringify({ tag_id: tagId })
      })
      .then(response => response.json())
      .then(data => {
        if (data.success) {
          // Remove the tag element
          const tagElement = button.closest('[data-supported-tag-id]');
          tagElement.remove();
          
          // Show success message
          showNotification('Tag removed successfully!', 'success');
        } else {
          showNotification(data.message || 'Failed to remove tag', 'error');
          // Re-enable button
          button.disabled = false;
          button.textContent = 'Remove';
        }
      })
      .catch(error => {
        console.error('Error:', error);
        showNotification('An error occurred while removing the tag', 'error');
        // Re-enable button
        button.disabled = false;
        button.textContent = 'Remove';
      });
    });
  }
  
  removeTagButtons.forEach(button => {
    attachRemoveTagListener(button);
  });
  
  function showNotification(message, type) {
    // Create a simple notification
    const notification = document.createElement('div');
    notification.className = `crayons-notice crayons-notice--${type === 'success' ? 'success' : 'error'} fixed top-4 right-4 z-50`;
    notification.textContent = message;
    
    document.body.appendChild(notification);
    
    // Remove after 3 seconds
    setTimeout(() => {
      notification.remove();
    }, 3000);
  }
  
  window.toggleSvgIconField = function(formId) {
    const field = document.getElementById(`svg-icon-field-${formId}`);
    const toggle = document.getElementById(`svg-toggle-${formId}`);
    
    if (field.style.display === 'none') {
      field.style.display = 'block';
      toggle.textContent = '- <%= t("views.subforems.edit.navigation_links.form.icon.alternative") %>';
    } else {
      field.style.display = 'none';
      toggle.textContent = '+ <%= t("views.subforems.edit.navigation_links.form.icon.alternative") %>';
    }
  };
  
  // Smooth scroll to section
  function scrollToSection(sectionId) {
    const section = document.getElementById(sectionId);
    if (section) {
      section.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
  }

  // Update active link based on scroll position
  function updateActiveLink() {
    const sections = document.querySelectorAll('[id^="section-"]');
    const links = document.querySelectorAll('.manage-sidebar-link');
    
    let currentSection = '';
    const scrollPosition = window.scrollY + 100; // Offset for better UX
    
    sections.forEach(section => {
      const sectionTop = section.offsetTop;
      const sectionHeight = section.offsetHeight;
      
      if (scrollPosition >= sectionTop && scrollPosition < sectionTop + sectionHeight) {
        currentSection = section.id;
      }
    });
    
    links.forEach(link => {
      link.classList.remove('active');
      if (link.dataset.section === currentSection) {
        link.classList.add('active');
      }
    });
  }

  // Handle sidebar link clicks
  const sidebarLinks = document.querySelectorAll('.manage-sidebar-link');
  
  sidebarLinks.forEach(link => {
    link.addEventListener('click', function(e) {
      e.preventDefault();
      const sectionId = this.dataset.section;
      scrollToSection(sectionId);
      
      // Update active state immediately
      sidebarLinks.forEach(l => l.classList.remove('active'));
      this.classList.add('active');
    });
  });
  
  // Update active link on scroll
  window.addEventListener('scroll', updateActiveLink);
  
  // Set initial active state
  updateActiveLink();
}

// Initialize on DOMContentLoaded for direct page loads
document.addEventListener('DOMContentLoaded', initializeSubforemEditPage);

// Initialize on InstantClick change for navigation via InstantClick
if (typeof InstantClick !== 'undefined') {
  InstantClick.on('change', function() {
    if (document.getElementById('main-content')?.classList.contains('manage-page-with-sidebar')) {
      initializeSubforemEditPage();
    }
  });
}
</script>
